#include <assert.h>
#include <gfx/iprogram.h>
#include <gfx/sharedshaderbinding.h>
#include <sharedvaluemanager.h>


#ifndef WIN32
#include <string.h>
#endif


ceSharedShaderBinding::ceSharedShaderBinding ()
	: iObject ()
{
  CE_OBJECT_CONSTR;
}


ceSharedShaderBinding::~ceSharedShaderBinding ()
{
	std::vector<SharedBinding>::iterator it;
	for (unsigned i=0, j=_bindings.size(); i<j; i++)
		{
			SharedBinding& sb = _bindings[i];
			if (sb.Value)
				{
					//sb.Value->Release ();
				}
		}
	_bindings.clear ();
}

void ceSharedShaderBinding::Add (const std::string& name, const ceProgramParameterName& parameter)
{
	SharedBinding sb;
	sb.Binding			= parameter;
	sb.SharedIndex	= -1;
  sb.SharedName		= std::string (name);
	sb.Value				= 0;
	_bindings.push_back (sb);
}

void ceSharedShaderBinding::Bind (ceSharedValueManager* manager, iProgram* program) 
{
	assert (manager);
	assert (program);
	for (unsigned i=0, j=_bindings.size (); i<j; i++)
		{
			SharedBinding& sb = _bindings[i];
			if (!sb.Value)
				{
					sb.SharedIndex = manager->GetIdx (sb.SharedName);
					sb.Value = manager->GetValue (sb.SharedIndex);
					if (!sb.Value)
						{
							continue;
						}
          sb.Value->AddRef();
				}

			iProgramParameter* param = program->GetParameter(sb.Binding);
			if (!param)
				{
					continue;
				}
			sb.Value->Bind (param);
		}

}
